//
//  payControlViewController.m
//  lmq
//
//  Created by 千翼网络科技 on 2017/3/13.
//  Copyright © 2017年 yuanxin. All rights reserved.
//

#import "payControlViewController.h"
#import "loginViewController.h"

#import "Config.h"
#import <Masonry/Masonry.h>
#import "NSObject+GstIP.h"
#import "WXApi.h"
#import <CommonCrypto/CommonDigest.h>
#import "homeViewController.h"
#import "AllMyOrderViewController.h"

#import <sys/socket.h>
#import <sys/sockio.h>
#import <sys/ioctl.h>
#import <net/if.h>
#import <arpa/inet.h>
#import <AlipaySDK/AlipaySDK.h>

#import "configddd.h"
#import "Order.h"
#import "NSObject+GstIP.h"
#include <ifaddrs.h>
#include <arpa/inet.h>
#include <net/if.h>

#import "RSADataSigner.h"

#define IOS_CELLULAR    @"pdp_ip0"
#define IOS_WIFI        @"en0"
#define IOS_VPN         @"utun0"
#define IP_ADDR_IPv4    @"ipv4"
#define IP_ADDR_IPv6    @"ipv6"

@interface payControlViewController ()

@end

@implementation payControlViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(popNotification:) name:@"pop" object:nil];
    
    UIButton *leftButton = [[UIButton alloc]initWithFrame:CGRectMake(screenScale(-20), 0, screenScale(50), screenScale(50))];
    [leftButton addTarget:self action:@selector(leftNavItemClick) forControlEvents:UIControlEventTouchUpInside];
    [leftButton setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    UIBarButtonItem *leftBarButton = [[UIBarButtonItem alloc]initWithCustomView:leftButton];
    self.navigationItem.leftBarButtonItem = leftBarButton;
    
    self.title = @"结算中心";
    self.view.backgroundColor = getColor(@"f5f5f5");
    self.bgView = [[UIView alloc]init];
    self.tittleLable = [[UILabel alloc]init];
    self.moneyImgLable = [[UILabel alloc]init];
    self.moneyNumLable = [[UILabel alloc]init];
    self.thread1View = [[UIView alloc]init];
    self.payWayLable = [[UILabel alloc]init];
    self.thread2View = [[UIView alloc]init];
    self.thread3View = [[UIView alloc]init];
    self.thread4View = [[UIView alloc]init];
    self.blancePayLable = [[UILabel alloc]init];
    self.blancePayBtn = [[UIButton alloc]init];
    self.wechatPayLable = [[UILabel alloc]init];
    self.wechatPayBtn = [[UIButton alloc]init];
    self.zfbPayLable = [[UILabel alloc]init];
    self.zfbPayBtn = [[UIButton alloc]init];
    self.payBtn = [[UIButton alloc]init];
    
    if ([_str isEqualToString:@"0.00"]) {
        
        self.thread3View.hidden = YES;
        self.thread4View.hidden = YES;
        self.wechatPayLable.hidden = YES;
        self.wechatPayBtn.hidden = YES;
        self.zfbPayLable.hidden = YES;
        self.zfbPayBtn.hidden = YES;
        self.bgView.frame = CGRectMake(0, 0, scrWidth(), screenScale(308));
    }
}

#pragma mark --- init

- (void)setBgView:(UIView *)bgView{
    
    _bgView = bgView;
    _bgView.frame = CGRectMake(0, 0, scrWidth(), screenScale(468));
    _bgView.backgroundColor = getColor(@"ffffff");
    [self.view addSubview:_bgView];
}

- (void)setTittleLable:(UILabel *)tittleLable{
    
    _tittleLable = tittleLable;
    _tittleLable.text = @"订单应付金额（含邮费）";
    _tittleLable.textColor = [UIColor blackColor];
    _tittleLable.font = get4sFont(14);
    _tittleLable.textAlignment = NSTextAlignmentCenter;
    [_bgView addSubview:_tittleLable];
    [_tittleLable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view).with.offset(screenScale(40));
        make.left.mas_equalTo(self.view).with.offset(0);
        make.width.mas_equalTo(scrWidth());
        make.height.mas_equalTo(screenScale(30));
    }];
}

- (void)setMoneyImgLable:(UILabel *)moneyImgLable{
    
    _moneyImgLable = moneyImgLable;
    _moneyImgLable.text = @"¥";
    _moneyImgLable.textColor = getColor(@"ff00000");
    _moneyImgLable.font = get4sFont(13);
    [_bgView addSubview:_moneyImgLable];
    [_moneyImgLable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view).with.offset(screenScale(100));
        make.left.mas_equalTo(self.view).with.offset(screenScale(250));
        make.width.mas_equalTo(screenScale(27));
        make.height.mas_equalTo(screenScale(27));
    }];
}

- (void)setMoneyNumLable:(UILabel *)moneyNumLable{

    _moneyNumLable = moneyNumLable;
    _moneyNumLable.text = _str;
    _moneyNumLable.textColor = getColor(@"ff0000");
    _moneyNumLable.font = get4sFont(19);
    _moneyNumLable.textAlignment = NSTextAlignmentLeft;
    [_bgView addSubview:_moneyNumLable];
    [_moneyNumLable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view).with.offset(screenScale(90));
        make.left.mas_equalTo(self.view).with.offset(screenScale(280));
        
        make.height.mas_equalTo(screenScale(40));
    }];
}

- (void)setThread1View:(UIView *)thread1View{
    
    _thread1View = thread1View;
    _thread1View.backgroundColor = getColor(@"f5f5f5");
    [_bgView addSubview:_thread1View];
    [_thread1View mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view).with.offset(screenScale(150));
        make.left.mas_equalTo(self.view).with.offset(0);
        make.width.mas_equalTo(scrWidth());
        make.height.mas_equalTo(screenScale(10));
    }];
}

- (void)setPayWayLable:(UILabel *)payWayLable{

    _payWayLable = payWayLable;
    _payWayLable.text = @"选择支付方式";
    _payWayLable.textColor = [UIColor blackColor];
    _payWayLable.font = get4sFont(13);
    [_bgView addSubview:_payWayLable];
    [_payWayLable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_thread1View).with.offset(screenScale(32));
        make.left.mas_equalTo(self.view).with.offset(screenScale(20));
        
        make.height.mas_equalTo(screenScale(28));
    }];
}

- (void)setThread2View:(UIView *)thread2View{

    _thread2View = thread2View;
    _thread2View.backgroundColor = getColor(@"f5f5f5");
    [_bgView addSubview:_thread2View];
    [_thread2View mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_thread1View).with.offset(screenScale(80));
        make.left.mas_equalTo(self.view).with.offset(screenScale(20));
        make.width.mas_equalTo(scrWidth());
        make.height.mas_equalTo(screenScale(2));
    }];
}

- (void)setBlancePayLable:(UILabel *)blancePayLable{
    
    _blancePayLable = blancePayLable;
    _blancePayLable.text = @"余额支付";
    _blancePayLable.textColor = getColor(@"565656");
    _blancePayLable.font = get4sFont(12);
    [_bgView addSubview:_blancePayLable];
    [_blancePayLable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_thread2View).with.offset(screenScale(25));
        make.left.mas_equalTo(self.view).with.offset(screenScale(20));
        
        make.height.mas_equalTo(screenScale(27));
    }];
}

- (void)setBlancePayBtn:(UIButton *)blancePayBtn{
    
    _blancePayBtn = blancePayBtn;
    _blancePayBtn.selected = YES;
    [_blancePayBtn setImage:[UIImage imageNamed:@"circile_b"] forState:UIControlStateNormal];
    [_blancePayBtn setImage:[UIImage imageNamed:@"duihao"] forState:UIControlStateSelected];
    [_bgView addSubview:_blancePayBtn];
    [_blancePayBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_thread2View).with.offset(screenScale(18));
        make.right.mas_equalTo(self.view).with.offset(screenScale(-20));
        
        
    }];
    [_blancePayBtn addTarget:self action:@selector(blancePayBtnClick) forControlEvents:UIControlEventTouchUpInside];
}

- (void)setThread3View:(UIView *)thread3View{
    
    _thread3View = thread3View;
    _thread3View.backgroundColor = getColor(@"f5f5f5");
    [_bgView addSubview:_thread3View];
    [_thread3View mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_thread2View).with.offset(screenScale(80));
        make.left.mas_equalTo(self.view).with.offset(screenScale(20));
        make.width.mas_equalTo(scrWidth());
        make.height.mas_equalTo(screenScale(2));
    }];
}

- (void)setWechatPayLable:(UILabel *)wechatPayLable{

    _wechatPayLable = wechatPayLable;
    _wechatPayLable.text = @"微信支付";
    _wechatPayLable.textColor = getColor(@"565656");
    _wechatPayLable.font = get4sFont(12);
    [_bgView addSubview:_wechatPayLable];
    [_wechatPayLable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_thread3View).with.offset(screenScale(25));
        make.left.mas_equalTo(self.view).with.offset(screenScale(20));
        
        make.height.mas_equalTo(screenScale(27));
    }];
}

- (void)setWechatPayBtn:(UIButton *)wechatPayBtn{

    _wechatPayBtn = wechatPayBtn;
    [_wechatPayBtn setImage:[UIImage imageNamed:@"circile_b"] forState:UIControlStateNormal];
    [_wechatPayBtn setImage:[UIImage imageNamed:@"duihao"] forState:UIControlStateSelected];
    [_bgView addSubview:_wechatPayBtn];
    [_wechatPayBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_thread3View).with.offset(screenScale(18));
        make.right.mas_equalTo(self.view).with.offset(screenScale(-20));
        
        
    }];
    [_wechatPayBtn addTarget:self action:@selector(wechatPayBtnClick) forControlEvents:UIControlEventTouchUpInside];
}

- (void)setThread4View:(UIView *)thread4View{
    
    _thread4View = thread4View;
    _thread4View.backgroundColor = getColor(@"f5f5f5");
    [_bgView addSubview:_thread4View];
    [_thread4View mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_thread3View).with.offset(screenScale(80));
        make.left.mas_equalTo(self.view).with.offset(screenScale(20));
        make.width.mas_equalTo(scrWidth());
        make.height.mas_equalTo(screenScale(2));
    }];
}

- (void)setZfbPayLable:(UILabel *)zfbPayLable{

    _zfbPayLable = zfbPayLable;
    _zfbPayLable.text = @"支付宝支付";
    _zfbPayLable.textColor = getColor(@"565656");
    _zfbPayLable.font = get4sFont(12);
    [_bgView addSubview:_zfbPayLable];
    [_zfbPayLable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_thread4View).with.offset(screenScale(25));
        make.left.mas_equalTo(self.view).with.offset(screenScale(20));
        
        make.height.mas_equalTo(screenScale(27));
    }];
}

- (void)setZfbPayBtn:(UIButton *)zfbPayBtn{

    _zfbPayBtn = zfbPayBtn;
    [_zfbPayBtn setImage:[UIImage imageNamed:@"circile_b"] forState:UIControlStateNormal];
    [_zfbPayBtn setImage:[UIImage imageNamed:@"duihao"] forState:UIControlStateSelected];
    [_bgView addSubview:_zfbPayBtn];
    [_zfbPayBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_thread4View).with.offset(screenScale(18));
        make.right.mas_equalTo(self.view).with.offset(screenScale(-20));
        
        
    }];
    [_zfbPayBtn addTarget:self action:@selector(zfbPayBtnClick) forControlEvents:UIControlEventTouchUpInside];
}

- (void)setPayBtn:(UIButton *)payBtn{
    
    _payBtn = payBtn;
    _payBtn.backgroundColor = [UIColor blackColor];
    _payBtn.titleLabel.font = get4sFont(14);
    [_payBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_payBtn setTitle:@"去付款" forState:UIControlStateNormal];
    [self.view addSubview:_payBtn];
    [_payBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(self.view).with.offset(0);
        make.left.mas_equalTo(self.view).with.offset(0);
        make.width.mas_equalTo(scrWidth());
        make.height.mas_equalTo(screenScale(80));
    }];
    [_payBtn addTarget:self action:@selector(payBtnClick) forControlEvents:UIControlEventTouchUpInside];
}

#pragma mark -------------Notification

- (void)popNotification:(NSNotification*)text{

    if ([text.userInfo[@"pop"]isEqualToString:@"yes"]) {
        
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[[UIApplication sharedApplication]keyWindow] animated:YES];
        hud.tag = 500;
        //提示文本
        hud.labelText = @"正在加载...";
        //是否有遮罩
        hud.dimBackground = YES;
        
        NSString *uidStr = [PublicFunction getConfigWithKey:@"uid"];
        NSString *tokenStr = [PublicFunction getConfigWithKey:@"token"];
        
        NSMutableDictionary *productParams = [[NSMutableDictionary alloc]init];
        [productParams setValue:uidStr forKey:@"member_id"];
        [productParams setValue:tokenStr forKey:@"token"];
        [productParams setValue:@"1" forKey:@"status"];
        if ([text.userInfo[@"payWay"]isEqualToString:@"ALIPay"]) {
            
            [productParams setValue:@"1" forKey:@"payment_type"];
        }else{
        
            [productParams setValue:@"2" forKey:@"payment_type"];
        }
        [productParams setValue:_moneyNumLable.text forKey:@"money"];
        
        [[MNetworkHandler sharedInstance]conURL:Pay_Result
                                    networkType:NetWorkPOST
                                         params:productParams
                                       delegate:nil
                                        showHUD:NO
                                   successBlock:^(id returnData) {
                                       if ([[returnData objectForKey:@"code"]intValue]==1) {
                                           
                                           [self.tabBarController setSelectedIndex:3];
                                           
                                           AllMyOrderViewController *allMyOrderVC = [[AllMyOrderViewController alloc]init];
                                           [self.navigationController pushViewController:allMyOrderVC animated:YES];
                                           [self.navigationController popToRootViewControllerAnimated:NO];
                                           [hud removeFromSuperview];
                                           
                                       }
                                       else if ([[returnData objectForKey:@"code"]intValue]==-1){
                                           
                                           [hud removeFromSuperview];
                                           //[PublicFunction showAlert:nil message:[returnData objectForKey:@"msg"] duration:5.0f];
                                       }
                                   } failureBlock:^(NSError *error) {
                                       
                                       [hud removeFromSuperview];
                                       NSLog(@"%@",error);
                                       [PublicFunction showAlert:nil message:@"没有连接网络" duration:10.0f];
                                   }];
    }
}

#pragma mark --- click

- (void)leftNavItemClick{

    [self.tabBarController setSelectedIndex:2];
    [self.navigationController popToRootViewControllerAnimated:NO];
}

- (void)wechatPayBtnClick{

    _wechatPayBtn.selected = YES;
    _zfbPayBtn.selected = NO;
    _blancePayBtn.selected = NO;
}

- (void)zfbPayBtnClick{

    _wechatPayBtn.selected = NO;
    _zfbPayBtn.selected = YES;
    _blancePayBtn.selected = NO;
}

- (void)blancePayBtnClick{

    _wechatPayBtn.selected = NO;
    _zfbPayBtn.selected = NO;
    _blancePayBtn.selected = YES;
}

//获取手机IP

- (NSString *)getDeviceIPIpAddresses{
    
    int sockfd =socket(AF_INET,SOCK_DGRAM, 0);
    
    //    if (sockfd <</span> 0) return nil;
    
    NSMutableArray *ips = [NSMutableArray array];
    
    int BUFFERSIZE =4096;
    
    struct ifconf ifc;
    
    char buffer[BUFFERSIZE], *ptr, lastname[IFNAMSIZ], *cptr;
    
    struct ifreq *ifr, ifrcopy;
    
    ifc.ifc_len = BUFFERSIZE;
    
    ifc.ifc_buf = buffer;
    
    if (ioctl(sockfd,SIOCGIFCONF, &ifc) >= 0){
        
        for (ptr = buffer; ptr < buffer + ifc.ifc_len; ){
            
            ifr = (struct ifreq *)ptr;
            
            int len =sizeof(struct sockaddr);
            
            if (ifr->ifr_addr.sa_len > len) {
                
                len = ifr->ifr_addr.sa_len;
                
            }
            
            ptr += sizeof(ifr->ifr_name) + len;
            
            if (ifr->ifr_addr.sa_family !=AF_INET) continue;
            
            if ((cptr = (char *)strchr(ifr->ifr_name,':')) != NULL) *cptr =0;
            
            if (strncmp(lastname, ifr->ifr_name,IFNAMSIZ) == 0)continue;
            
            memcpy(lastname, ifr->ifr_name,IFNAMSIZ);
            
            ifrcopy = *ifr;
            
            ioctl(sockfd,SIOCGIFFLAGS, &ifrcopy);
            
            if ((ifrcopy.ifr_flags &IFF_UP) == 0)continue;
            
            NSString *ip = [NSString stringWithFormat:@"%s",inet_ntoa(((struct sockaddr_in *)&ifr->ifr_addr)->sin_addr)];
            
            [ips addObject:ip];
        }
    }
    
    close(sockfd);
    NSString *deviceIP =@"";
    
    for (int i=0; i < ips.count; i++){
        
        if (ips.count >0){
            
            deviceIP = [NSString stringWithFormat:@"%@",ips.lastObject];
        }
    }
    NSLog(@"deviceIP========%@",deviceIP);
    return deviceIP;
}

- (void)payBtnClick{

    NSLog(@"去付款");
    
    // 登陆判断
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[[UIApplication sharedApplication]keyWindow] animated:YES];
    hud.tag = 500;
    //提示文本
    hud.labelText = @"正在加载...";
    //是否有遮罩
    hud.dimBackground = YES;
    
    NSMutableDictionary *productParams=[[NSMutableDictionary alloc]init];
    [productParams setValue: [PublicFunction getConfigWithKey:@"token"] forKey:@"token"];
    
    [[MNetworkHandler sharedInstance]conURL:Is_Login
                                networkType:NetWorkPOST
                                     params:productParams
                                   delegate:nil
                                    showHUD:NO
                               successBlock:^(id returnData) {
                                   if ([[returnData objectForKey:@"code"]intValue]==1) {
                                       
                                       [self pay];
                                       [hud removeFromSuperview];
                                   }else{
                                       
                                       [hud removeFromSuperview];
                                       loginViewController *loginVc =[[loginViewController alloc]init];
                                       [self.navigationController presentViewController:loginVc animated:YES completion:^{}];
                                   }
                               } failureBlock:^(NSError *error) {
                                   
                                   [hud removeFromSuperview];
                                   NSLog(@"%@",error);
                                   [PublicFunction showAlert:nil message:@"没有连接网络" duration:10.0f];
                               }];
}

- (void)pay{

    if (_wechatPayBtn.selected) {
        
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[[UIApplication sharedApplication]keyWindow] animated:YES];
        hud.tag = 500;
        //提示文本
        hud.labelText = @"正在加载...";
        //是否有遮罩
        hud.dimBackground = YES;
        
        NSString *uidStr=[PublicFunction getConfigWithKey:@"uid"];
        NSString *tokenStr=[PublicFunction getConfigWithKey:@"token"];
        NSString *all_number = [PublicFunction getConfigWithKey:@"all_number"];
        NSString *order_id = [PublicFunction getConfigWithKey:@"order_id"];
        
        NSMutableDictionary *productParams=[[NSMutableDictionary alloc]init];
        [productParams setValue:uidStr forKey:@"member_id"];
        [productParams setValue:tokenStr forKey:@"token"];
        [productParams setValue:[self getDeviceIPIpAddresses] forKey:@"ip"];
        [productParams setValue:all_number forKey:@"all_number"];
        [productParams setValue:order_id forKey:@"order_id"];
        
        [[MNetworkHandler sharedInstance]conURL:Add_WeiXinPay
                                    networkType:NetWorkPOST
                                         params:productParams
                                       delegate:nil
                                        showHUD:NO
                                   successBlock:^(id returnData) {
                                       if ([[returnData objectForKey:@"code"]intValue]==1) {
                                           
                                           _appid = returnData[@"data"][@"appid"];
                                           _partnerid = returnData[@"data"][@"mch_id"];
                                           _prepayid = returnData[@"data"][@"prepay_id"];
                                           _noncestr = returnData[@"data"][@"nonce_str"];
                                           _sign = returnData[@"data"][@"sign"];
                                           
                                           
                                           [PublicFunction saveConfig:[returnData[@"data"] objectForKey:@"appid"] forKey:@"appid"];
                                           [PublicFunction saveConfig:[returnData[@"data"] objectForKey:@"mch_id"] forKey:@"mch_id"];
                                           [PublicFunction saveConfig:[returnData[@"data"] objectForKey:@"prepay_id"] forKey:@"prepay_id"];
                                           [PublicFunction saveConfig:[returnData[@"data"] objectForKey:@"nonce_str"] forKey:@"nonce_str"];
                                           [PublicFunction saveConfig:[returnData[@"data"] objectForKey:@"sign"] forKey:@"sign"];
                                           
                                           [PublicFunction saveConfig:[returnData[@"data"] objectForKey:@"trade_type"] forKey:@"trade_type"];
                                           
                                           [hud removeFromSuperview];
                                           
                                           [self startPay];
                                           
                                       }
                                       else{
                                           
                                           [hud removeFromSuperview];
                                           [PublicFunction showAlert:nil message:[returnData objectForKey:@"msg"] duration:5.0f];
                                       }
                                   } failureBlock:^(NSError *error) {
                                       
                                       [hud removeFromSuperview];
                                       NSLog(@"%@",error);
                                       [PublicFunction showAlert:nil message:@"没有连接网络" duration:10.0f];
                                   }];
    }
    else if (_zfbPayBtn.selected) {
        
        NSDictionary *dict =[[NSDictionary alloc]initWithObjectsAndKeys:@"yes",@"payWay", nil];
        NSNotification *notification =[NSNotification notificationWithName:@"payWay" object:nil userInfo:dict];
        [[NSNotificationCenter defaultCenter] postNotification:notification];
        [self aliPay];
    }
    else if (_blancePayBtn.selected){
        
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[[UIApplication sharedApplication]keyWindow] animated:YES];
        hud.tag = 500;
        //提示文本
        hud.labelText = @"正在加载...";
        //是否有遮罩
        hud.dimBackground = YES;
        
        NSString *uidStr=[PublicFunction getConfigWithKey:@"uid"];
        NSString *tokenStr=[PublicFunction getConfigWithKey:@"token"];
        NSString *all_number = [PublicFunction getConfigWithKey:@"all_number"];
        NSString *order_id = [PublicFunction getConfigWithKey:@"order_id"];
        
        NSMutableDictionary *productParams=[[NSMutableDictionary alloc]init];
        [productParams setValue:uidStr forKey:@"member_id"];
        [productParams setValue:tokenStr forKey:@"token"];
        [productParams setValue:all_number forKey:@"all_number"];
        [productParams setValue:order_id forKey:@"order_id"];
        
        [[MNetworkHandler sharedInstance]conURL:Balance_Pay
                                    networkType:NetWorkPOST
                                         params:productParams
                                       delegate:nil
                                        showHUD:NO
                                   successBlock:^(id returnData) {
                                       if ([[returnData objectForKey:@"code"]intValue]==1) {
                                           
                                           
                                           [hud removeFromSuperview];
                                           [PublicFunction showAlert:nil message:[returnData objectForKey:@"msg"] duration:5.0f];
                                           
                                           [self.tabBarController setSelectedIndex:3];
                                           
                                           AllMyOrderViewController *allMyOrderVC = [[AllMyOrderViewController alloc]init];
                                           [self.navigationController pushViewController:allMyOrderVC animated:YES];
                                           [self.navigationController popToRootViewControllerAnimated:NO];
                                           [hud removeFromSuperview];
                                       }
                                       else{
                                           
                                           [hud removeFromSuperview];
                                           [PublicFunction showAlert:nil message:[returnData objectForKey:@"msg"] duration:5.0f];
                                       }
                                   } failureBlock:^(NSError *error) {
                                       
                                       [hud removeFromSuperview];
                                       NSLog(@"%@",error);
                                       [PublicFunction showAlert:nil message:@"没有连接网络" duration:10.0f];
                                   }];
    }
}

#pragma mark ------------------- 微信支付

-(void)startPay{
    
    //判断用户当前是否下载微信／是否支持微信支付
    if (![WXApi isWXAppInstalled]) {//表示用户没有安装微信
        
        NSLog(@"需要安装微信才能使用微信支付");
        
    } else if (![WXApi isWXAppSupportApi]){
        
        //表示当前不支持微信支付
        //提示用户当前环境不支持微信支付
        NSLog(@"不支持微信支付");
    }
    NSLog(@"安装了微信，而且支持微信支付");
    //============================================================
    // V3&V4支付流程实现
    // 注意:参数配置请查看服务器端Demo
    // 更新时间：2015年11月20日
    //============================================================
    
    NSDate*senddate = [NSDate date];
    NSLog(@"date1时间戳= %ld",time(NULL));
    NSDateFormatter *dateformatter = [[NSDateFormatter alloc]init];
    NSString*date1 = [dateformatter stringFromDate:senddate];
    
    //调起微信支付
    PayReq* req             = [[PayReq alloc] init];
    
    
    req.openID              = [PublicFunction getConfigWithKey:@"appid"];
    req.partnerId           = [PublicFunction getConfigWithKey:@"mch_id"];
    req.prepayId            = [PublicFunction getConfigWithKey:@"prepay_id"];
    req.package             = @"Sign=WXPay";
    req.nonceStr            = [PublicFunction getConfigWithKey:@"nonce_str"];
    req.timeStamp           = [date1 intValue];
    req.sign                = [self createMD5SingForPay:[PublicFunction getConfigWithKey:@"appid"]
                                              partnerid:[PublicFunction getConfigWithKey:@"mch_id"]
                                               prepayid:[PublicFunction getConfigWithKey:@"prepay_id"]
                                                package:@"Sign=WXPay"
                                               noncestr:[PublicFunction getConfigWithKey:@"nonce_str"]
                                              timestamp:[date1 intValue]];
    
    BOOL result = [WXApi sendReq:req];
    NSLog(@"%d",result);
    
    NSDictionary *dict =[[NSDictionary alloc]initWithObjectsAndKeys:@"yes",@"payWay", nil];
    NSNotification *notification =[NSNotification notificationWithName:@"payWay" object:nil userInfo:dict];
    [[NSNotificationCenter defaultCenter] postNotification:notification];
    
    //[self.navigationController popToRootViewControllerAnimated:YES];
    
}

//统一下单-第一次签名
-(void)createMd5Sign:(NSMutableDictionary*)dict
{
    NSMutableString *contentString  =[NSMutableString string];
    
    NSArray *keys = [dict allKeys];
    
    //按字母顺序排序
    NSArray *sortedArray = [keys sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        return [obj1 compare:obj2 options:NSNumericSearch];
    }];
    
    //拼接字符串
    for (NSString *categoryId in sortedArray) {
        
        if (   ![[dict objectForKey:categoryId] isEqualToString:@""]
            && ![[dict objectForKey:categoryId] isEqualToString:@"sign"]
            && ![[dict objectForKey:categoryId] isEqualToString:@"key"]
            )
        {
            [contentString appendFormat:@"%@=%@&", categoryId, [dict objectForKey:categoryId]];
        }
    }
    //添加商户密钥key字段
    [contentString appendFormat:@"key=%@",_partnerid];
    
    NSLog(@"contentString = %@",contentString);
    
    //MD5 获取Sign签名
    NSString *md5Sign =[self md5:contentString];
    
    //
}

//创建发起支付时的sige签名--二次签名

-(NSString *)createMD5SingForPay:(NSString *)appid_key partnerid:(NSString *)partnerid_key prepayid:(NSString *)prepayid_key package:(NSString *)package_key noncestr:(NSString *)noncestr_key timestamp:(UInt32)timestamp_key{
    
    NSMutableDictionary *signParams = [NSMutableDictionary dictionary];
    [signParams setObject:appid_key forKey:@"appid"];
    [signParams setObject:noncestr_key forKey:@"noncestr"];
    [signParams setObject:package_key forKey:@"package"];
    [signParams setObject:partnerid_key forKey:@"partnerid"];
    [signParams setObject:prepayid_key forKey:@"prepayid"];
    [signParams setObject:[NSString stringWithFormat:@"%u",(unsigned int)timestamp_key] forKey:@"timestamp"];
    
    NSMutableString *contentString  =[NSMutableString string];
    NSArray *keys = [signParams allKeys];
    //按字母顺序排序
    NSArray *sortedArray = [keys sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        return [obj1 compare:obj2 options:NSNumericSearch];
    }];
    //拼接字符串
    for (NSString *categoryId in sortedArray) {
        if (   ![[signParams objectForKey:categoryId] isEqualToString:@""]
            && ![[signParams objectForKey:categoryId] isEqualToString:@"sign"]
            && ![[signParams objectForKey:categoryId] isEqualToString:@"key"]
            )
        {
            [contentString appendFormat:@"%@=%@&", categoryId, [signParams objectForKey:categoryId]];
        }
    }
    //添加商户密钥key字段
    //注意此处一定要添加上商户密钥
    [contentString appendFormat:@"key=%@", @"AD85dsfgDSEd875412sdgWU54921njhD"];
    NSString *result = [self md5:contentString];
    
    NSLog(@"result = %@",result);
    return result;
}

// MD5加密算法
-(NSString *) md5:(NSString *)str
{
    const char *cStr = [str UTF8String];
    //加密规则，因为逗比微信没有出微信支付demo，这里加密规则是参照安卓demo来得
    unsigned char result[16]= "0123456789abcdef";
    CC_MD5(cStr, (CC_LONG)strlen(cStr), result);
    //这里的x是小写则产生的md5也是小写，x是大写则md5是大写，这里只能用大写，逗比微信的大小写验证很逗
    return [NSString stringWithFormat:
            @"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}

#pragma mark ------------------- 支付宝支付
- (void)aliPay {
    // 支付宝支付
    /* 在调用支付宝支付之前，需要我们将相关订单参数发送至我们的后台服务器，由后台服务器进行签名处理，
     并返回客户端所有相关参数，客户端直接使用参数调起支付宝支付。
     */
    /*
     *商户的唯一的parnter和seller。
     *签约后，支付宝会为每个商户分配一个唯一的 parnter 和 seller。
     */
    
    /*============================================================================*/
    /*=======================需要填写商户app申请的===================================*/
    /*============================================================================*/
    NSString *partner = @"2017030906133732";
    NSString *seller = @"2088621432093435";
    
    NSString *privateKey = @"MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDkG9NH3MbrUS/oZBtm6W8rsDP6WBiBTp8jrmdRtpC+tqwv0l8MmBXVIXAFM4FHSo2jEGFwo+dI+Ok4zn+2gz3ctyOSNxO2jAFjh2TLYcSGjN6si/uWbhlWmQaibbKypcInsOBf0tM7ADAcxc9vYjGiVrDgiiTgcpd/nxvI9PqgB/bnfX9qIT9ozUrLL6fu4xH9RjYArrDS5lgjcKiEkU6JrHyagXT9b3wOEQGk4fp5WETfu66wOw11G4TlI1IvZ455MbVBOX7Jzud/p0aLaO5joDsCULd0jg+PgXlPsKE1ivpuvlZ22USeb/vvyKgX/wrIjOwI/5ddd66wJBaoc7nJAgMBAAECggEBALdB74S9RwYILI/r1OPhyBF2Ntv56H4B1vIIjDLmk/TTtxOYVAo/KNMYUPGsxkCrEY0efNnMo+RJLL0ZkRrk508pxqcSHoE6i2cVgBGxEvzxsXc34sCg5TRgLidSMA08A/Z1MF1rd43gAccr2BHo9m0wbluGQEgdZ7786YqR3cOv/cnuFWb0pl4lpGC6+Pw+xKWEA1YNlecfqotyBHrwBcKXT6Z0S06LeRNCSSqNL5MpOG96pyKMfP4jyhhtq4WDvtbTaMFJP/kbKGUCVlLOV7CPncN/mN3vgfeDZ54+qwB6A1mUL5FixgzbOtigzr5tEHfOlw/zxR6nxZjwQsG/v4ECgYEA+veic9Z4SxXhe0spkKHm0tdtcSG1OmVQ2j7y9pv4VXuYyxcZe1xBELqIZEd7IiTGpLFgFzKvs8RdBqjygfSJz98ezA9vG72Umk+OolHub/En6AcOdxNaXWulSXkHzkAl0hrPkDD82Lhsjpkmzegzxe19X1RA+JpzdjQrkettQHECgYEA6K7X/Xno096i9mGfotDYPhiiB/Hej2vUrr9Yiw9NmbWBsxv3xWpIgb9K/68urR0GJUQXZrT4b6jfjhH85R836FYUXyI2SGkuyQ5+rtkGD6cMZWxbV/L21Mw7S7wUzX9jq6h0ZtvqsJ9prQY2iWelqQrF9fXeq+W7sJx/5ztmutkCgYBzo+ORKMPpJT3ux+VxJYjsoiNlu7h8He8xgUwG4jt9eCQhgJVXSF0azjjGrEFKrFNz09+JEOvxE4wh43tK8lkGFbNlJ790sthkekAo/0O1BRP0UDwUFjDPVyikQEaefORwebYmpMv9OI2c72j3/ATPMO1SHcqKQvDtCIEDDc4boQKBgBVYVMAP+ufUuKZZdkd9WRj5MYQBECWgAra1Hu5CzR+YovlHS4d0pIoifkLOUz3WN8YbZPorB89WcouZ4tUx8/MAUoYXoVsrKvuOtNhdWEz/SgfT1N1QkIwc4COmcVIYqZAJuAPnkLP7K7qPo1kfhPbo4hgaIf8q5/jfomwX6uihAoGAeNQc4SaMMf/QRam4oSovU3ekuQv4ETtXodXaRRwlFjxSq0nZFYeaomqTr2Au/L3DqC3MHPs3en9+BhKj1MI5kjiuxxrA4vysit+uSq/AepSxN+sYcguXLxPvU01v27qEhueohwKKZ2tdxAaai4ytdbBY7XeMzR2a/IF+j+C/Kp0=";
    
    /*============================================================================*/
    /*============================================================================*/
    /*============================================================================*/
    
    //partner和seller获取失败,提示
    if ([partner length] == 0 ||
        [seller length] == 0 ||
        [privateKey length] == 0)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                        message:@"缺少partner或者seller或者私钥。"
                                                       delegate:self
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
        return;
    }
    
    /*生成订单信息及签名
    */
    //将商品信息赋予AlixPayOrder的成员变量
    Order* order = [Order new];
    
    // NOTE: app_id设置
    order.app_id = partner;
    
    // NOTE: 支付接口名称
    order.method = @"alipay.trade.app.pay";
    
    // NOTE: 参数编码格式
    order.charset = @"utf-8";
    
    // NOTE: 当前时间点
    NSDateFormatter* formatter = [NSDateFormatter new];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    order.timestamp = [formatter stringFromDate:[NSDate date]];
    
    // NOTE: 支付版本
    order.version = @"2.0";
    
    // NOTE: sign_type 根据商户设置的私钥来决定
    order.sign_type = (privateKey.length > 1)?@"RSA2":@"RSA";
    
    //order.notify_url = @"https://api.xx.com/receive_notify.htm";
    
    // NOTE: 商品数据
    order.biz_content = [BizContent new];;
    order.biz_content.body = @"商品信息";
    order.biz_content.seller_id = seller;
    order.biz_content.subject = @"乐麦圈支付";
    order.biz_content.out_trade_no = [PublicFunction getConfigWithKey:@"all_number"]; //订单ID（由商家自行制定）
    order.biz_content.timeout_express = @"30m"; //超时时间设置
    order.biz_content.total_amount = [NSString stringWithFormat:@"%0.2f", [_str floatValue]]; //商品价格
    
    //将商品信息拼接成字符串
    NSString *orderInfo = [order orderInfoEncoded:NO];
    NSString *orderInfoEncoded = [order orderInfoEncoded:YES];
    NSLog(@"orderSpec = %@",orderInfo);
    
    // NOTE: 获取私钥并将商户信息签名，外部商户的加签过程请务必放在服务端，防止公私钥数据泄露；
    //       需要遵循RSA签名规范，并将签名字符串base64编码和UrlEncode
    NSString *signedString = nil;
    
    RSADataSigner* signer = [[RSADataSigner alloc] initWithPrivateKey:((privateKey.length > 1)?privateKey:privateKey)];
    
    if ((privateKey.length > 1)) {
        signedString = [signer signString:orderInfo withRSA2:YES];
    } else {
        signedString = [signer signString:orderInfo withRSA2:NO];
    }
    
    // NOTE: 如果加签成功，则继续执行支付
    if (signedString != nil) {
        //应用注册scheme,在AliSDKDemo-Info.plist定义URL types
        NSString *appScheme = @"ali2017030906133732";
        
        // NOTE: 将签名成功字符串格式化为订单字符串,请严格按照该格式
        NSString *orderString = [NSString stringWithFormat:@"%@&sign=%@",
                                 orderInfoEncoded, signedString];
        
        // NOTE: 调用支付结果开始支付
        [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
            NSLog(@"reslut = %@",resultDic);
        }];
    }
    
    
}


- (NSString *)generateTradeNO
{
    static int kNumber = 15;
    
    NSString *sourceStr = @"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    NSMutableString *resultStr = [[NSMutableString alloc] init];
    srand((unsigned)time(0));
    for (int i = 0; i < kNumber; i++)
    {
        unsigned index = rand() % [sourceStr length];
        NSString *oneStr = [sourceStr substringWithRange:NSMakeRange(index, 1)];
        [resultStr appendString:oneStr];
    }
    return resultStr;
}


@end
